<template>
  <div>
    <div class="head-title borderTop">
      <div class="head-title-text">可供范围</div>
      <div class="head-right">同步更新可供商品状态：
        <span v-if="undefined === updateSupplierSupplyRangeExecuteVO">无</span>
        <span
          v-if="undefined !== updateSupplierSupplyRangeExecuteVO"
        >状态（{{
            undefined !== updateSupplierSupplyRangeExecuteVO.endTime ? '已结束' : '同步中'
          }}）</span>
        <span
          v-if="undefined !== updateSupplierSupplyRangeExecuteVO && undefined !== updateSupplierSupplyRangeExecuteVO.startTime"
        >开始时间（{{
            updateSupplierSupplyRangeExecuteVO.startTimeText
          }}）</span>
        <span
          v-if="undefined !== updateSupplierSupplyRangeExecuteVO && undefined !== updateSupplierSupplyRangeExecuteVO.endTime"
        >结束时间（{{
            updateSupplierSupplyRangeExecuteVO.endTimeText
          }}）</span>
        <span
          v-if="undefined !== updateSupplierSupplyRangeExecuteVO && undefined !== updateSupplierSupplyRangeExecuteVO.endTime"
        >执行时长（{{
            updateSupplierSupplyRangeExecuteVO.executeTime
          }}）</span>
        <el-button
          v-if="undefined !== updateSupplierSupplyRangeExecuteVO && undefined === updateSupplierSupplyRangeExecuteVO.endTime"

          size="mini"
          @click="reloadSyncUpdateData"
        >
          刷新
        </el-button>
      </div>
    </div>
    <el-form v-if="1!==deliveryMethod" label-width="100px" style="margin-top: 20px">
      <el-form-item v-if="!disabled" :label="1===deliveryMethod?'可供仓库：' : '可供范围：'">
        <el-row>
          <el-col :span="6">
            <area-cascader :area-values.sync="areaValues" @checkNodes="handleAreaCheckNodes"/>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" style="margin-left: 10px;" :disabled="disabled" @click="handleAddLocation">添加
            </el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <el-row v-if="1!==deliveryMethod">
      <el-col :span="12">
        <el-table class="table-default" :data="areaArray" border>
          <el-table-column prop="geoAreaFullName" label="省 市 区"/>
          <el-table-column label="操作" width="100" align="center">
            <template v-slot="scope">
              <el-button type="danger" width="100px" :disabled="disabled" @click="handleRemoveLocation(scope.$index)">移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-form v-if="1!==deliveryMethod&&!disabled" label-width="180px" style="margin-top: 20px">
      <el-form-item label="区域内不可配送机构：">
        <el-button type="primary" :disabled="disabled" @click="handleAddUnDeliveryOrganization">添加不可配送机构
        </el-button>
      </el-form-item>
    </el-form>
    <el-table
      v-if="1!==deliveryMethod"
      class="table-default"
      :data="excludeOrganizationArray"
      border
      style="margin-top: 20px"
    >
      <el-table-column prop="excludeOrganizationId" label="机构编号" width="170" align="center"/>
      <el-table-column prop="excludeOrganizationName" label="机构名称" align="center"/>
      <el-table-column prop="areaName" label="机构地址" align="center"/>
      <el-table-column label="操作" width="110" align="center">
        <template v-slot="scope">
          <el-button
            type="danger"
            :disabled="disabled"
            @click="handleRemoveUnDeliveryOrganization('excludeOrganizationArray',scope.$index)"
          >移除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-form v-if="!disabled" label-width="180px" style="margin-top: 20px">
      <el-form-item :label="1 !== deliveryMethod ? '区域外可配送机构：':'可配送仓库：'">
        <el-button type="primary" :disabled="disabled" @click="handleAdditionalOrganization">
          {{ 1 !== deliveryMethod ? '添加区域外可配送机构' : '添加可配送仓库' }}
        </el-button>
      </el-form-item>
    </el-form>
    <el-table class="table-default" :data="additionalOrganizationArray" border style="margin-top: 20px">
      <el-table-column prop="additionalOrganizationId" label="机构编号" width="170" align="center"/>
      <el-table-column prop="additionalOrganizationName" label="机构名称" align="center"/>
      <el-table-column prop="areaName" label="机构地址" align="center"/>
      <el-table-column label="操作" width="110" align="center">
        <template v-slot="scope">
          <el-button
            type="danger"
            :disabled="disabled"
            @click="handleRemoveUnDeliveryOrganization('additionalOrganizationArray',scope.$index)"
          >移除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- <el-row style="margin-top: 30px">
      <el-button type="warning" @click="handleSave">保存</el-button>
    </el-row> -->
    <organization-select-dialog ref="organizationSelectDialogRef"/>
  </div>
</template>
<script>
import AreaCascader from '@/components/AreaCascader/supplyRange'
import OrganizationSelectDialog from '@/components/organizationSelect/organizationSelect'

export default {
  name: 'SupplyRange',
  components: {
    AreaCascader,
    OrganizationSelectDialog
  },
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    deliveryMethod: {
      type: Number,
      default: 0
    },
    info: {
      type: Object,
      default() {
      }
    },
    areaList: {
      type: Array,
      required: true,
      default() {
        return []
      }
    },
    excludeOrganizationList: {
      type: Array,
      required: true,
      default() {
        return []
      }
    },
    additionalOrganizationList: {
      type: Array,
      required: true,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      areaValues: [],
      areaGroup: []
    }
  },
  computed: {
    updateSupplierSupplyRangeExecuteVO: {
      get() {
        if (undefined !== this.info.updateSupplierSupplyRangeExecuteVO) {
          const executeVO = this.info.updateSupplierSupplyRangeExecuteVO
          executeVO.startTimeText = this.$commonUtils.getShowAllTime(executeVO.startTime)
          if (undefined !== executeVO.endTime) {
            executeVO.endTimeText = this.$commonUtils.getShowAllTime(executeVO.endTime)
            executeVO.executeTime = ((executeVO.endTime - executeVO.startTime) / 1000).toFixed(0) + '秒'
          }
          return executeVO
        }
        return undefined
      }
    },
    areaArray: {
      get() {
        return this.areaList
      },
      set(val) {
        this.$emit('update:areaList', val)
      }
    },
    excludeOrganizationArray: {
      get() {
        return this.excludeOrganizationList
      },
      set(val) {
        this.$emit('update:excludeOrganizationList', val)
      }
    },
    additionalOrganizationArray: {
      get() {
        return this.additionalOrganizationList
      },
      set(val) {
        this.$emit('update:additionalOrganizationList', val)
      }
    }
  },
  watch: {
    deliveryMethod(val, oldVal) {
      if (this.disabled === false) {
        if (oldVal === 1 && val !== 1) {
          this.areaArray = []
          this.additionalOrganizationArray = []
          this.excludeOrganizationArray = []
        } else if (oldVal !== 1 && val === 1) {
          this.areaArray = []
          this.excludeOrganizationArray = []
          this.additionalOrganizationArray = []
        }
      }
    }
  },
  methods: {
    hasUpdateSupplyRange() {
      this.$emit('hasUpdate')
    },
    handleAddLocation() {
      const areaArray = []
      this.areaGroup.forEach(item => {
        if (item.length === 3) {
          const index = this.areaArray.findIndex(res => res.area === item[2].geoAreaId)
          if (index < 0) {
            areaArray.push({
              province: item[0].geoAreaId,
              city: item[1].geoAreaId,
              area: item[2].geoAreaId,
              geoAreaFullName: item[0].areaName + '、' + item[1].areaName + '、' + item[2].areaName
            })
          }
        }
        if (item.length === 2) {
          const index = this.areaArray.findIndex(res => res.city === item[1].geoAreaId)
          if (index < 0) {
            areaArray.push({
              province: item[0].geoAreaId,
              city: item[1].geoAreaId,
              area: item[1].geoAreaId,
              geoAreaFullName: item[0].areaName + '、' + item[1].areaName
            })
          }
        }
        if (item.length === 1) {
          const index = this.areaArray.findIndex(res => res.province === item[0].geoAreaId)
          if (index < 0) {
            areaArray.push({
              province: item[0].geoAreaId,
              city: item[0].geoAreaId,
              area: item[0].geoAreaId,
              geoAreaFullName: item[0].areaName
            })
          }
        }
      })
      this.areaArray = [...this.areaArray, ...areaArray]
      this.hasUpdateSupplyRange()
    },
    handleRemoveLocation(index) {
      this.areaArray.splice(index, 1)
      this.hasUpdateSupplyRange()
    },
    handleAreaCheckNodes(event) {
      this.areaGroup = event
    },
    handleAddUnDeliveryOrganization() {
      this.$refs.organizationSelectDialogRef.init(event => {
        if (event) {
          event.forEach(item => {
            const index = this.excludeOrganizationArray.findIndex(res => res.excludeOrganizationId === item.organizationId)
            if (index < 0) {
              this.excludeOrganizationArray.push({
                excludeOrganizationId: item.organizationId,
                excludeOrganizationName: item.organizationName
              })
              this.hasUpdateSupplyRange()
            }
          })
        }
      })
    },
    handleRemoveUnDeliveryOrganization(arr, index) {
      this[arr].splice(index, 1)
      this.hasUpdateSupplyRange()
    },
    handleAdditionalOrganization() {
      this.$refs.organizationSelectDialogRef.init(event => {
        if (event) {
          event.forEach(item => {
            const index = this.additionalOrganizationList.findIndex(res => res.additionalOrganizationId === item.organizationId)
            if (index < 0) {
              this.additionalOrganizationList.push({
                additionalOrganizationId: item.organizationId,
                additionalOrganizationName: item.organizationName
              })
              this.hasUpdateSupplyRange()
            }
          })
        }
      }, {
        functionSort: this.deliveryMethod === 1 ? 'chainWarehouse' : 'store'
      })
    },
    handleRemoveAdditionalOrganization(index) {
      this.additionalOrganizationList.splice(index, 1)
    },
    async reloadSyncUpdateData() {
      let loading
      try {
        loading = this.$loading({
          lock: true,
          text: '请稍等...'
        })
        const res = await this.$api.getSupplierSupplyRange({
          supplierOrganizationId: this.info.supplierOrganizationId,
          returnDetail: false
        }, {showLoading: false})
        if (undefined !== res.updateSupplierSupplyRangeExecuteVO) {
          const executeVO = res.updateSupplierSupplyRangeExecuteVO
          executeVO.startTimeText = this.$commonUtils.getShowTime(executeVO.startTime)
          if (undefined !== executeVO.endTime) {
            executeVO.endTimeText = this.$commonUtils.getShowTime(executeVO.endTime)
            executeVO.executeTime = ((executeVO.endTime - executeVO.startTime) / 1000).toFixed(0) + '秒'
          }
          this.info.updateSupplierSupplyRangeExecuteVO = executeVO
        }
      } catch (err) {
        console.error(err)
      } finally {
        loading && loading.close()
      }
    },
    handleSave() {
    }
  }
}
</script>
<style lang="scss" scope>
.head-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.head-right {
  font-size: 14px;
}
</style>
